package com.ssm.shiro;

import com.ssm.dao.SysMenuDao;
import com.ssm.dao.UserDao;
import com.ssm.entity.SysMenuEntity;
import com.ssm.entity.UserVo;
import com.ssm.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

//认证
public class shiroReaml extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private UserDao userDao;
    private static final transient Logger log = LoggerFactory.getLogger(UserVo.class);

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("AuthenticationInfo:"+token);

        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        //查询用户信息
        UserVo user = userService.queryByUserName(username);
        System.out.println("姓名："+ user.getUsername());
        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //密码错误
        if (!password.equals(user.getPassword())) {
            System.out.println("密码错误啊");
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        //模拟对数据库用户密码进行MD5加密后的密码
       //SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),"fc1709d0a95a6be30bc5926fdb7f22f4",  ByteSource.Util.bytes(user.getUsername()),getName());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password, getName());

        String getName = getName();
        log.info("reamlName:"+getName);
        return info;
    }
//
//    public static void main(String[] args){
//        String a = "MD5";
//        Object password = "123456";
//
//        int count = 1024;
//        Object result = new SimpleHash(a, password, null, count);
//        System.out.println(result);
//    }

//    @Override
//    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        Object userVo  =  principals.getPrimaryPrincipal();
//        Set<String> roles = new HashSet<>();
//        if("admin".equals(userVo)){
//            roles.add("admin");
//        }else if("user".equals(userVo)){
//            roles.add("user");
//        }
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
//        return info;
//    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserVo user = (UserVo) principals.getPrimaryPrincipal();
        Long userId = user.getUserId();

       // List<String> permsList = (List<String>) J2CacheUtils.get(Constant.PERMS_LIST + userId);

        List<String> permsList;
        Set<String> roles = new HashSet<>();
        roles.add(user.getUsername());
        //系统管理员，拥有最高权限
        if (1 == user.getUserId()) {
            List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>());
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = userDao.queryAllPerms(user.getUserId());
        }


        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        if (permsList != null && permsList.size() != 0) {
            for (String perms : permsList) {
                if (StringUtils.isBlank(perms)) {
                    continue;
                }
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        info.setStringPermissions(permsSet);
        return info;
    }
}
